package com.gallop.mq.core.template;

import com.gallop.mq.MQProperties;
import com.gallop.mq.MQTemplate;
import com.gallop.mq.core.MQExecutorProvider;
import com.gallop.mq.core.MQMessageCodec;
import com.gallop.mq.core.MQMessageDispatcher;
import com.gallop.mq.core.exception.MQException;
import com.gallop.mq.core.template.handler.registry.MessageDeliveryHandlerRegistry;
import com.gallop.mq.core.template.handler.registry.RegistryHolder;
import com.gallop.mq.core.template.handler.registry.RegistryPreprocessor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.time.Duration;
import java.util.function.BiConsumer;
import java.util.function.Consumer;

@Data
@Slf4j
public class ZeroMQTemplate implements MQTemplate, RegistryHolder {

    private MQProperties properties;
    private MQMessageCodec codec;
    private MQMessageDispatcher dispatcher;
    private MessageDeliveryHandlerRegistry handlerRegistry;

    @Override
    public void init(MQProperties properties, MQMessageDispatcher dispatcher, MQMessageCodec codec, MQExecutorProvider executorProvider, MessageDeliveryHandlerRegistry handlerRegistry) throws MQException {
        setProperties(properties);
        setDispatcher(dispatcher);
        setCodec(codec);
        // TODO executor
        this.initRegistry(handlerRegistry);
        // TODO init zmq
    }

    @Override
    public void onDispose() {
        throw new MQException("not implemented yet.");
    }

    @Override
    public void send(Object message, String topic) {
        throw new MQException("not implemented yet.");
    }

    @Override
    public <P> void request(Object message, String topic, Consumer<P> onResponse) {
        request(message, topic, null, onResponse);
    }

    @Override
    public <P> void request(Object message, String topic, Duration requestTimeout, Consumer<P> onResponse) {
        request(message, topic, requestTimeout, onResponse, (req, ex) -> log.error("", ex));
    }

    @Override
    public <P> void request(Object message, String topic, Duration requestTimeout, Consumer<P> onResponse, BiConsumer<Object, Exception> onError) {
        throw new MQException("not implemented yet.");
    }

    @Override
    public <P> P request(Object message, String topic, Duration receiveTimeout) throws InterruptedException {
        throw new MQException("not implemented yet.");
    }

    @Override
    public MessageDeliveryHandlerRegistry.InitializerBuilder registryInitializer() {
        return MessageDeliveryHandlerRegistry.InitializerBuilder.newBuilder()
                .setPreprocessor(RegistryPreprocessor.builder()
                        // TODO build handler registry
                        .build());
    }
}
